package com.huanmeiqi.demo.persistence.two.aspect;

import com.huanmeiqi.demo.persistence.two.DBContextHolder;
import com.huanmeiqi.demo.persistence.two.annotation.BindDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author cq.Wang
 * @date 2018/6/14 13:42
 * @description
 */
@Aspect
@Component
public class BindDataSourceAspect {

    private BindDataSource annotation;

    /**
     * 声明切面
     */
    @Pointcut("@annotation(com.huanmeiqi.demo.persistence.two.annotation.BindDataSource)")
    public void pointCut() {

    }

    @Before(value = "pointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        // 切点所在的类
        Class targetClass = point.getTarget().getClass();
        // 使用了注解的方法
        String methodName = point.getSignature().getName();
        // 方法参数类型
        Class[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
        // 获取方法对象
        Method method = targetClass.getMethod(methodName, parameterTypes);
        Objects.requireNonNull(method);
        // 获取注解对象
        annotation = method.getAnnotation(BindDataSource.class);
        // 设置数据源
        DBContextHolder.setDatabaseType(annotation.value());

    }

}
